<template>
  <div class="receive-list">
    <div class="mb-4">
      <el-radio-group
        v-model="queryParams.status"
        @change="handleStatusChange"
      >
        <el-radio :value="-1">全部</el-radio>
        <el-radio :value="0">待发放</el-radio>
        <el-radio :value="1">已发放</el-radio>
      </el-radio-group>

      <el-button
        :disabled="!selectedRows.length"
        class="ml-4"
        size="default"
        type="primary"
        @click="handleBatchSend"
      >
        批量发放
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="displayData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="用户"
        prop="wxUserInfo"
      >
        <template #default="{ row }">
          {{ row?.wxUserInfo?.nickname }}
          <span class="ml2">{{ row.openid }}</span>
        </template>
      </el-table-column>
      <el-table-column label="金额">
        <template #default="{ row }">
          <el-tag v-if="row.status === 1">已发放</el-tag>
          <el-tag
            v-else
            type="danger"
          >
            未发放
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="金额">
        <template #default="{ row }">{{ row.amount }}元</template>
      </el-table-column>
      <el-table-column
        label="发放时间"
        prop="updateTime"
      ></el-table-column>
      <el-table-column
        label="领取时间"
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="操作"
        width="120"
      >
        <template #default="{ row }">
          <el-button
            v-if="row.status === 0"
            v-reClick
            size="small"
            type="primary"
            @click="handleSingleSend(row)"
          >
            发放
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="mt-4 flex justify-end">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { DrawRedPacketWinnerEntity } from "@/api/project/lottery";
import { getWinnerList, manualSendRedPacket } from "@/api/project/lottery";

const props = defineProps<{
  sourceId: string;
  sourceType: string;
}>();

const loading = ref(false);
const dataSource = ref<DrawRedPacketWinnerEntity[]>([]);
const selectedRows = ref<DrawRedPacketWinnerEntity[]>([]);
const queryParams = ref({
  sourceId: props.sourceId,
  sourceType: props.sourceType,
  status: -1
});

const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});

const displayData = computed(() => {
  const { current, pageSize } = pagination.value;
  const start = (current - 1) * pageSize;
  const end = start + pageSize;
  return dataSource.value.slice(start, end);
});

// 获取列表数据
const fetchList = async () => {
  loading.value = true;
  try {
    const res = await getWinnerList(queryParams.value);
    if (res.data) {
      dataSource.value = res.data;
      pagination.value.total = dataSource.value.length;
    }
  } catch (error) {
    ElMessage.error("获取列表失败");
  } finally {
    loading.value = false;
  }
};

// 状态切换
const handleStatusChange = () => {
  pagination.value.current = 1;
  selectedRows.value = [];
  fetchList();
};

// 表格选择变化
const handleSelectionChange = (rows: DrawRedPacketWinnerEntity[]) => {
  selectedRows.value = rows;
};

// 页码变化
const handleCurrentChange = (current: number) => {
  pagination.value.current = current;
};

// 每页条数变化
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.current = 1;
};

// 单个发放
const handleSingleSend = async (row: DrawRedPacketWinnerEntity) => {
  try {
    await ElMessageBox.confirm("确认要发放该红包吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    });

    const res = await manualSendRedPacket({ ids: [row.id] });
    if (res) {
      ElMessage.success("发放成功");
      fetchList();
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("发放失败");
    }
  }
};

// 修改批量发放方法，添加确认框
const handleBatchSend = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning("请选择要发放的记录");
    return;
  }

  try {
    await ElMessageBox.confirm(`确认要发放选中的 ${selectedRows.value.length} 个红包吗？`, "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    });

    const ids = selectedRows.value.map(item => item.id);
    const res = await manualSendRedPacket({ ids });
    if (res) {
      ElMessage.success("发放成功");
      selectedRows.value = [];
      fetchList();
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("发放失败");
    }
  }
};

onMounted(() => {
  fetchList();
});
</script>

<style scoped>
.receive-list {
  margin: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 16px;
}

.ml-4 {
  margin-left: 16px;
}

.flex {
  display: flex;
}

.justify-end {
  justify-content: flex-end;
}
</style>
